import dash
import dash_bootstrap_components as dbc
import numpy as np
from dash import dcc, html, Input, Output
import plotly.express as px
import pandas as pd
import ExcelRead
from country import get_cn_name

################################# 初始化数据 ######################################

# 取出城镇化数据
urban_df = ExcelRead.read_excel_to_df(
    ".//assets//API_SP.URB.TOTL.IN.ZS_DS2_en_excel_v2_29.xls")
# 取出供水数据
supply_dict = ExcelRead.read_csv_to_df(
    ".//assets//share-of-the-population-using-safely-managed-drinking-water-sources.csv")

# 取出城镇化国家
urban_country = urban_df.index.to_list()
# 取出供水国家
supply_dict.keys()
supply_valid_keys = [key for key, country_data in supply_dict.items() if not pd.isna(country_data[1][0])]

# 找出城镇化数据和供水数据的交集
intersection = set(urban_country) & set(supply_valid_keys)
intersection_list = sorted(list(intersection))
print("交集的长度:", len(intersection_list))
print("交集的元素:", intersection_list)

# 根据两个国家的交集，建立选择框
# country_options = [{'label': get_cn_name(item), 'value': item} for item in intersection_list]
# 如果get_cn_name没找到，则使用item
country_options = [{'label': get_cn_name(item) if get_cn_name(item) else item, 'value': item}
                   for item in intersection_list
                   ]


# 用于初始化fig
def empty_fig():
    empty_df = pd.DataFrame()
    emp_fig = px.scatter(empty_df)
    return emp_fig


fig = empty_fig()


def update_fig(country_name):
    global fig
    # urban_data = urban_df.loc[country_name]
    #
    # fig = px.scatter(urban_data,
    #                  title=f'{country_name}  城镇人口占比与城镇供水率比较',
    #                  color_discrete_sequence=['red'])

    country_data = supply_dict.get(country_name)
    temp_dict = {'Year': country_data[0], 'Urban usage': country_data[1]}
    country_df = pd.DataFrame(temp_dict)
    # country_df.rename() = '城镇供水率'
    fig = px.scatter(country_df,
                     x='Year',
                     y='Urban usage',
                     title=f'{country_name}  城镇人口占比与城镇供水率比较',
                     color_discrete_sequence=['blue'])

    urban_data = urban_df.loc[country_name]

    fig.add_trace(px.scatter(urban_data,
                             title=f'{country_name}  城镇人口占比与城镇供水率比较',
                             color_discrete_sequence=['red']).data[0])


update_fig("Algeria")

# 初始化Dash应用
# app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app = dash.Dash(__name__)
# 应用布局
app.layout = html.Div(
    dbc.Container(
        [
            html.Br(),
            html.Br(),
            html.H2("城镇人口占比与城镇供水率比较", style={'textAlign': 'center'}),
            # html.Div(style={'height': '20px'}),
            html.Br(),
            html.Br(),
            dbc.Row(
                dbc.Col(
                    dcc.Dropdown(
                        id='country-select',
                        options=country_options,
                        # multi=True
                    )
                )
            ),
            dbc.Row(
                dbc.Col(
                    dcc.Graph(
                        id='gdp-population-scatter',
                        figure=fig,
                        # figure=px.scatter(df2, x='Year', y=['GDP', 'Population'],
                        #                    labels={'value': 'Value', 'variable': 'Metric'},
                        #                    title='GDP and Population Over Time',
                        #                    color_discrete_sequence=px.colors.qualitative.Pastel),
                        # config={'displayModeBar': False}
                    ),
                    # width=12
                )
            )
        ],
        fluid=True
    )
)


@app.callback(Output('gdp-population-scatter', 'figure'),
              Input('country-select', 'value'))
def country2chart(country):
    global fig

    country_data = supply_dict.get(country)

    if (country_data is not None) and (not np.isnan(country_data[1][0])):
        try:
            update_fig(country)
            # fig = None  图形不会再变化
            # fig = empty_fig()
        except Exception as err:
            print(err)
    # else:
    #     fig = None
    return fig


server = app.server
# 运行应用
if __name__ == '__main__':
    app.run_server(debug=True)
